package logic

import (
	"context"
	"errors"
	"video-guard/models/cache"
	"video-guard/models/mysql"
	"video-guard/pkg"

	"video-guard/videorpc/internal/svc"
	"video-guard/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PasswordUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPasswordUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PasswordUpdateLogic {
	return &PasswordUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PasswordUpdateLogic) PasswordUpdate(in *videorpc.PasswordUpdateRequest) (*videorpc.PasswordUpdateResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.UserInfo

	err := user.FirstUserById(mysql.DB, in.UserId)
	if err != nil {
		return nil, errors.New("该用户不存在")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+user.PhoneNum).Result()

	if result != in.SmsCode {
		return nil, errors.New("验证码错误")
	}

	if in.NewPassword != in.OkPassword {
		return nil, errors.New("两次输入的密码不一致")
	}

	user.Pwd = pkg.Md5(in.NewPassword)

	err = user.PasswordUpdate(mysql.DB, in.UserId)
	if err != nil {
		return nil, errors.New("密码重置失败")
	}

	return &videorpc.PasswordUpdateResponse{
		UserId: int64(user.ID),
	}, nil
}
